import network
import utime as time


connect_status_4g = False
connect_status_eth = False
connect_status_wifi = False


def connect_wifi(ssid,pwd):
    global connect_status_wifi
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    time.sleep(2)
    wlan.connect(ssid, pwd)
    while not wlan.isconnected():
        pass
    connect_status_wifi = True
    print('wifi connected: ', wlan.ifconfig())
    return connect_status_wifi


def getwifiFlag():
    global connect_status_wifi
    return  connect_status_wifi



lte = network.LTE()
def connect_4g():
    global connect_status_4g, iccid,version
    if not lte.isconnected():
        print("Connecting to 4g...")
        lte.active(True)
        lte.connect()
        # 循环等待直到连接成功
        while True:  
            if lte.isconnected():
                connect_status_4g = True
                print("4G connected:", lte.status())
                version = lte.version()
                iccid = lte.iccid()
                print('''version:{}\niccid:{}'''.format(version,iccid))
                break
            else:
                print('connect_status_4g',connect_status_4g)
                connect_status_4g = False
                break
        return connect_status_4g
    
def get4gFlag():
    global connect_status_4g
    return  connect_status_4g

def get_4g_info():
    global version,iccid
    return version,iccid


eth = network.LAN()
def connect_eth():
    global connect_status_eth
    if not eth.isconnected():
        print("Connecting to eth...")
        eth.active(True)
        # 循环等待直到连接成功
        a = 0
        while not eth.isconnected():
            a+=1
            time.sleep_ms(50)
            if a >=100:
                break
        if a>=100 :
            print('!!!! lan connect fail  !!!!\r',a)
            connect_status_eth = False
        else:
            connect_status_eth = True
        print("eth connected:", eth.ifconfig())
        connect_status_eth = True
        return connect_status_eth

def getethFlag():
    global connect_status_eth
    return  connect_status_eth

def connect_lan(ip,subnet,gateway,dns):
    # 定义全局变量
    if not eth.isconnected():
        print((ip,subnet,gateway,dns))
        eth.ifconfig((ip,subnet,gateway,dns))
        eth.active(True)
        # 循环等待直到连接成功
        a = 0
        while not eth.isconnected():
            a+=1
            time.sleep_ms(50)
            if a >=100:
                break
        if a>=100 :
            print('!!!! lan connect fail  !!!!\r',a)
            connect_status_eth = False
        else:
            connect_status_eth = True
        print("eth connected:", eth.ifconfig())
        connect_status_eth = True
        return connect_status_eth